import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'animate.css'
import { startTokenRefresh } from './utils/tokenUtils'
import { addDebugCommands } from './utils/debugUtils'
import { useUserStore } from './stores/user'
import webSocketManager from './utils/websocket'

const app = createApp(App)
const pinia = createPinia()

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(pinia)
app.use(router)
app.use(ElementPlus)

// 初始化用户状态
const userStore = useUserStore()
userStore.initializeAuth()

// 启动token自动刷新（延迟执行，避免与路由守卫冲突）
setTimeout(() => {
  const token = localStorage.getItem('token')
  if (token) {
    // 动态导入token工具函数
    import('./utils/tokenUtils').then(({ isTokenExpired, startTokenRefresh }) => {
      if (!isTokenExpired(token)) {
        startTokenRefresh()
        console.log('Token自动刷新已启动')

        // 启动WebSocket连接
        webSocketManager.connect(token).then(() => {
          console.log('WebSocket连接已建立')
        }).catch(error => {
          console.error('WebSocket连接失败:', error)
        })
      } else {
        // token已过期，清除登录状态
        console.log('Token已过期，清除登录状态')
        localStorage.removeItem('token')
        localStorage.removeItem('refreshToken')
        localStorage.removeItem('userInfo')
      }
    }).catch(error => {
      console.error('启动token自动刷新失败:', error)
    })
  }
}, 1000) // 延迟1秒执行

// 添加调试命令（仅在开发环境）
if (import.meta.env.DEV) {
  addDebugCommands()
}

app.mount('#app')